package com.vne.skyemart.util;

import java.util.HashSet;
import java.util.List;

import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;


public class CommonUtils {
	

	 public static HashSet<String> getAllUserOnline() {
	    	try {
	    		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(SkyemartConfig.getInstance().getServletContextInit());
	    		SessionRegistry sr = (SessionRegistry) ctx.getBean("sessionRegistry");	
	    		List<Object> principals = sr.getAllPrincipals();				
				if (principals != null && principals.size() > 0) {
					HashSet<String> listUserOnlie = new HashSet<String>();
					for (Object object : principals) 				
						listUserOnlie.add(((User)object).getUsername());
					return listUserOnlie;
				}
				return null;
			} catch (Exception e) {
				return null;
			}
	    }
	 
	 public static boolean isUserOnline(String username) {
	    	try {
	    		return getAllUserOnline().contains(username);
			} catch (Exception e) {
				return false;
			}
	    }
}
